﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using CID.Domain.Users;

namespace CID.Web.Models.Users
{
    public class UserViewModel : BaseNamedViewModel<IUser>
    {
        #region Properties
        [Display(Name = "User Name")]
        [Required(ErrorMessage = "You must provide an user name (network alias) for the User")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "You must provide an email address for the User")]
        [DataType(DataType.EmailAddress, ErrorMessage = "You must provide a valid email address for the User")]
        public string Email { get; set; }

        public bool Enabled { get; set; }

        [Display(Name="Assigned Roles")]
        public List<UserRoleAssignmentViewModel> AssignedRoles { get; set; }
        #endregion
        
        public UserViewModel() : base()
        {
            CreateAssignedRolesList();
        }

        public UserViewModel(IUser user) : base(user)
        {
            Name = user.Name;
            UserName = user.UserName;
            Enabled = user.Enabled;
            Email = user.Email;
            CreateAssignedRolesList();
            foreach (UserRoleAssignmentViewModel userRoleAssignment in AssignedRoles)
                userRoleAssignment.Assigned = user.Is(userRoleAssignment.UserRole);

        }

        private void CreateAssignedRolesList()
        {
            AssignedRoles = new List<UserRoleAssignmentViewModel>();
            foreach (UserRole userRole in Enum.GetValues(typeof(UserRole)))
                AssignedRoles.Add(new UserRoleAssignmentViewModel() { UserRole = userRole });
        }

        public override void UpdateModel(IUser user)
        {
            base.UpdateModel(user);
            user.Name = Name;
            user.UserName = UserName;
            user.Email = Email;
            user.Enabled = Enabled;
            var currentUserRoles = user.AssignedRoles.Select(x => x.UserRole).ToList();
            var newUserRoles = AssignedRoles.Where(x => x.Assigned).Select(x => x.UserRole);

            foreach (var newlyAssignedRole in newUserRoles.Where(x => !currentUserRoles.Contains(x)))
                user.AssignRole(newlyAssignedRole);

            foreach (var notLongerAssignedRole in currentUserRoles.Where(x => !newUserRoles.Contains(x)))
                user.UnassignRole(notLongerAssignedRole);
        }
    }
}